#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

template<class K, class V>
struct AVLTreeNode
{
	pair<K, V> _kv;
	AVLTreeNode<K, V>* _left;
	AVLTreeNode<K, V>* _right;
	AVLTreeNode<K, V>* _parent;//为了更新平衡因子
	int _bf;//balance factor 平衡因子

	AVLTreeNode(const pair<K, V>& kv)
		:_kv(kv)
		, _left(nullptr)
		, _right(nullptr)
		,_parent(nullptr)
		,_bf(0)
	{}
};

template<class K, class V>
class AVLTree
{
	typedef AVLTreeNode<K, V> Node;
public:
	//编译器默认生成构造的条件：没有写任何的构造函数，就会生成；但是此时写了拷贝构造，就生不成其他的默认构造了
	AVLTree() = default;// default强制生成默认构造

	AVLTree(const pair<K, V>& t)
	{
		_root = Copy(t._rooot);
	}

	AVLTree<K, V>& operator=(AVLTree<K, V> t)
	{
		swap(_root, t._root);
		return *this;
	}

	~AVLTree()
	{
		Destroy(_root);
		_root = nullptr;
	}

	bool Insert(const pair<K, V>& kv)
	{
		if (_root == nullptr)
		{
			_root = new Node(kv);
			return true;
		}

		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_kv.first < kv.first)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_kv.first > kv.first)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}

		cur = new Node(kv);
		if (parent->_kv.first < kv.first)
		{
			parent->_right = cur;
		}
		else
		{
			parent->_left = cur;
		}
		cur->_parent = parent;

		//更新平衡因子
			while (parent)
			{
				if (cur == parent->_left)//插入在parent左,平衡因子--
					parent->_bf--;
				else
					parent->_bf++;//在右++


				if (parent->_bf == 0)//平衡，就退出
				{
					break;
				}
				else if (parent->_bf == 1 || parent->_bf == -1)//往上更新 
				{
					//继续往上更新
					cur = parent;
					parent = parent->_parent;
				}
				else if (parent->_bf == 2 || parent->_bf == -2)
				{
					//不平衡了，旋转处理
				}
				else
				{
					assert(false);//出现其他问题，进行断言
				}
			}


		return true;

	}

	Node* Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				cur = cur->_left;
			}
			else
			{
				return cur;
			}
		}

		return nullptr;
	}

	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}

private:
	void Destroy(Node* root)
	{
		if (_root == nullptr)
		{
			return;
		}
		Destoroy(root->_left);
		Destoroy(root->_rught);

		delete root;
	}

	Node* Copy(Node* root)
	{
		if (root == nullptr)
		{
			return nullptr;
		}

		Node* newRoot = new Node(root->_key, root->_value);
		newRoot->_left = Copy(root->_left);
		newRoot->_left = Copy(root->_right);

		return newRoot;
	}


private:
	Node* _root = nullptr;
};